<?php
require_once('../../core.inc.php');
require_once('Model/SiteManage.php');
require_once('View/Smarty.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
require_once('Model/Pager.php');
require_once('Model/Uploader.php');
require_once('Plugin/FileManager.php');

$sys = new Model_SiteManage();
$sys->checkLogin();
$params       = $_REQUEST;
$smarty       = new View_Smarty($params);
$file_manager = new Model_FileManager();
$smarty->assign('file_manager', $file_manager);

if (isset($params['do']) && function_exists('exec_' . $params['do'])){
   $params['op'] = call_user_func('exec_' . $params['do'], $params, &$smarty, &$file_manager); 
}
if (isset($params['op']) && function_exists('op_' . $params['op'])){
    call_user_func('op_' . $params['op'], $params, &$smarty, &$file_manager);
}
else{
    call_user_func('op_search', $params, &$smarty, &$file_manager);
}
// 検索、一覧
function op_search($params, &$smarty, &$file_manager)
{
    if (!isset($params['search'])){
        $search                = array();
        $search['tyep']        = '';
        $search['status']      = '';
        $search['tags']        = '';
        $search['category_id'] = '';
        $params['search']      = $search;
    }
    else{
        if (!empty($params['search']['tags'])){
            $params['search']['tag'] = explode(',', $params['search']['tags']);
        }
        $page_id = isset($params['page_id']) && $params['page_id'] > 1 ? $params['page_id'] : 1;
        $max_row = 20;
        $pager   = new Model_Pager();
        $pager->getPagerInfo($file_manager->getListCount($params['search']), $page_id, $max_row);
        $list = $file_manager->getList($params['search'], 'id asc', $max_row, ($max_row * ($page_id - 1)));
        $smarty->assign('list', $list);
        $smarty->assign('pager', $pager);
    }
    $params['search']['status'] = isset($params['search']['status']) ? $params['search']['status'] : '';
    $smarty->assign('search', $params['search']);
    $smarty->display('file_manager/file_manager_index.html');
}
// 新規登録
function op_regist($params, &$smarty, &$file_manager)
{
    if (!isset($params['forms'])){
        $forms = array();
        foreach($file_manager->getFormKeys() as $key){
            $forms[$key] = '';
        }
        $params['forms']   = $forms;
    }
    else{
        $keys = explode(',', 'status,class_id,park_flag');
        foreach($keys as $key){
            if (!isset($params['forms'][$key])){
                $params['forms'][$key] = '';
            }
        }
    }
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('file_manager/file_manager_form.html');
//print_r($params);
}
function exec_validate_regist_form(&$params, &$smarty, &$file_manager)
{
    $err = array();
    // 詳細画像の空削除
    if(isset($params['forms']['img'])){
        if(isset($params['forms']['img'][3])){
            foreach($params['forms']['img'][3] as $n => $cache){
                if($cache == '' && (!isset($params['forms']['img_comment'][3][$n]) || $params['forms']['img_comment'][3][$n] == '')){
                    unset($params['forms']['img'][3][$n]);
                    unset($params['forms']['img_comment'][3][$n]);
                }
            }
        }
    }
    //
    if ($file_manager->validate($params['forms'], $err)){
        return exec_regist_form($params, $smarty, $file_manager);
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
print_r($err);
    return 'regist';
}
function exec_regist_form(&$params, &$smarty, &$file_manager)
{
    $params['forms']['zip_code']    = ($params['forms']['zipcode1'] != '' && $params['forms']['zipcode2'] != '' ? $params['forms']['zipcode1'].'-'.$params['forms']['zipcode2']   : '');
    $params['forms']['years']       = ($params['forms']['years_y']  != '' && $params['forms']['years_m']  != '' ? sprintf('%04d-%02d-01', $params['forms']['years_y'], $params['forms']['years_m']) : '');
    $params['forms']['st_datetime'] = ($params['forms']['st_date']  != '' && $params['forms']['st_time']  != '' ? $params['forms']['st_date'].' '.sprintf('%02d:00', $params['forms']['st_time']) : '');
    $params['forms']['ed_datetime'] = ($params['forms']['ed_date']  != '' && $params['forms']['ed_time']  != '' ? $params['forms']['ed_date'].' '.sprintf('%02d:00', $params['forms']['ed_time']) : '');
    $id = $file_manager->insert($params['forms']);
    // img
    if(isset($params['forms']['img'])){
        $uploader = new Model_Uploader();
        foreach($params['forms']['img'] as $type => $img){
            foreach($img as $key => $cache){
                if($cache != ''){
// 本来 site_id で振り分け
$base_name = $id . '_' . $type; 
$move_to   = SiteManageRootDir . '/htdocs/investment/images/';
//
                    $filename = $uploader->moveCacheImage($cache, $move_to, $base_name);
                    $data = array(
                            'file_manager_id' => $id,
                            'type'           => $type,
                            'filename'       => $filename,
                            'comment'        => (isset($params['forms']['img_comment'][$type][$key]) ? $params['forms']['img_comment'][$type][$key] : '')
                            );
                    $img_id = $file_manager->insertImage($data);
                }
            }
        }
    }
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=regist_complete&id=' . $id);
    exit();
}
function op_regist_complete($params, &$smarty, &$file_manager)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $smarty->assign('forms', array('id' => $params['id']));
    }
    $smarty->assign('message', '登録が完了しました');
    $smarty->display('file_manager/file_manager_form.html');
}
// 編集
function op_edit($params, &$smarty, &$file_manager)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $id = $params['id'];
    if (!isset($params['forms'])){
        $forms = $file_manager->get($id);
        $forms['zipcode1'] = !empty($forms['zip_code']) ? substr($forms['zip_code'], 0, 3) : '';
        $forms['zipcode2'] = !empty($forms['zip_code']) ? substr($forms['zip_code'], 4, 4) : '';
        $forms['st_date']  = !empty($forms['st_datetime']) ? substr($forms['st_datetime'], 0, 10) : '';
        $forms['st_time']  = !empty($forms['st_datetime']) ? substr($forms['st_datetime'], 12, 2) : '0';
        $forms['ed_date']  = !empty($forms['ed_datetime']) ? substr($forms['ed_datetime'], 0, 10) : '';
        $forms['ed_time']  = !empty($forms['ed_datetime']) ? substr($forms['ed_datetime'], 12, 2) : '0';
        $forms['years_y']  = !empty($forms['years']) ? substr($forms['years'], 0, 4) : '';
        $forms['years_m']  = !empty($forms['years']) ? substr($forms['years'], 5, 2) : '';
        $forms['img']         = array();
        $forms['img_comment'] = array();
        foreach($file_manager->getImageList($id) as $data){
// 本来は site_id で振り分け
$forms['img'][$data['type']][] = 'http://investment.bird-i.co.jp/images/' . $data['filename'];
if($data['type'] == 3){
    $forms['img_comment'][3][] = $data['comment'];
} 
        }
        $params['forms']   = $forms;
    }
    else{
        $keys = explode(',', 'status,class_id,park_flag');
        foreach($keys as $key){
            if (!isset($params['forms'][$key])){
                $params['forms'][$key] = '';
            }
        }
    }
    $smarty->assign('id', $id);
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('file_manager/file_manager_form.html');
}
function exec_validate_update_form(&$params, &$smarty, &$file_manager)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $err = array();
    // 詳細画像の空削除
    if(isset($params['forms']['img'])){
        if(isset($params['forms']['img'][3])){
            foreach($params['forms']['img'][3] as $n => $cache){
                if($cache == '' && (!isset($params['forms']['img_comment'][3][$n]) || $params['forms']['img_comment'][3][$n] == '')){
                    unset($params['forms']['img'][3][$n]);
                    unset($params['forms']['img_comment'][3][$n]);
                }
            }
        }
    }
    //
    if ($file_manager->validate($params['forms'], $err)){
        return exec_update_form($params, $smarty, $file_manager);
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'regist';
}
function exec_update_form(&$params, &$smarty, &$file_manager)
{
    $id = $params['id'];
    
	if($_POST['mode'] == "delete")
	{
		$params['forms']['enabled'] = 0;
	}
	
    $params['forms']['zip_code']    = ($params['forms']['zipcode1'] != '' && $params['forms']['zipcode2'] != '' ? $params['forms']['zipcode1'].'-'.$params['forms']['zipcode2']   : '');
    $params['forms']['years']       = ($params['forms']['years_y']  != '' && $params['forms']['years_m']  != '' ? sprintf('%04d-%02d-01', $params['forms']['years_y'], $params['forms']['years_m']) : '');
    $params['forms']['st_datetime'] = ($params['forms']['st_date']  != '' && $params['forms']['st_time']  != '' ? $params['forms']['st_date'].' '.sprintf('%02d:00', $params['forms']['st_time']) : '');
    $params['forms']['ed_datetime'] = ($params['forms']['ed_date']  != '' && $params['forms']['ed_time']  != '' ? $params['forms']['ed_date'].' '.sprintf('%02d:00', $params['forms']['ed_time']) : '');
    $file_manager->update($id, $params['forms']);
    // img
    if(isset($params['forms']['img'])){
        $registed = array();
        foreach($file_manager->getImageList($id) as $data){
            $registed[$data['type']][$data['filename']] = $data;
        }
        $uploader = new Model_Uploader();
        foreach($params['forms']['img'] as $type => $img){
            foreach($img as $key => $cache){
                if($cache != '' && !preg_match('/http/', $cache)){
// 本来 site_id で振り分け
$base_name = $id . '_' . $type;
$move_to   = SiteManageRootDir . '/htdocs/investment/images/';
//
                    $filename = $uploader->moveCacheImage($cache, $move_to, $base_name);
                    $data = array(
                            'file_manager_id' => $id,
                            'type'           => $type,
                            'filename'       => $filename,
                            'comment'        => (isset($params['forms']['img_comment'][$type][$key]) ? $params['forms']['img_comment'][$type][$key] : '')
                    );
                    if(($type == 1 || $type == 2) && isset($registed[$type])){
                        $file_manager->updateImage($data);
                    }
                    else{
                        $img_id = $file_manager->insertImage($data);
                    }
                }
                elseif($type == 3){
                    // コメント更新
                    $data = array(
                            'file_manager_id' => $id,
                            'type'           => $type,
                            'filename'       => array_pop(explode('/',$cache)),
                            'comment'        => (isset($params['forms']['img_comment'][$type][$key]) ? $params['forms']['img_comment'][$type][$key] : '')
                    );
                    $file_manager->updateImageComment($data);
                }
            }
        }
        // type = 3 削除
        foreach($img as $cache){
            if(preg_match('/http/', $cache)){
                $filename = array_pop(explode('/', $cache));
                if(isset($registed[3][$filename])){
                    unset($registed[3][$filename]);
                }
            }
        }
        if(!empty($registed[3])){
            foreach($registed[3] as $filename => $data){
                $file_manager->deleteImageById($data['id']);
            }
        }
        //
    }
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=edit_complete&id=' . $id);
    exit();
}
function op_edit_complete($params, &$smarty, &$file_manager)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $smarty->assign('forms', array('id' => $params['id']));
    }
    $smarty->assign('message', '更新が完了しました');
    $smarty->display('file_manager/file_manager_form.html');
}

?>